<template>
  <el-card>
    <template #header>
      <h2>为级别 [{{ levelId }}] 添加项目</h2>
    </template>

    <el-row gutter="20">
      <el-col :span="12">
        <h3>可选项目</h3>
        <el-table :data="available" stripe>
          <el-table-column prop="name" label="名称" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button
                size="small"
                @click="select(row)"
                :disabled="isConfigured(row) || isSelected(row)"
              >
                添加
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col :span="12">
        <h3>已选项目</h3>
        <el-table :data="selected" stripe>
          <el-table-column prop="name" label="名称" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="deselect(row)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div class="footer-btns">
      <el-button type="primary" @click="confirmAdd">确认</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const axios = inject('axios')
const router = useRouter()
const route = useRoute()

// 从 query 中获取要操作的 levelId
const levelId = Number(route.query.levelId)

// 后端已配置到此级别的项目列表（用于过滤和禁用“添加”）
const existingConfigured = ref([])
// 本次操作中用户选中的新项目
const selected = ref([])
// 全部启用状态的项目列表
const fullList = ref([])

// 计算“可选项目”列表 = 全部 - 已配置 - 已选
const available = computed(() =>
  fullList.value.filter(
    p =>
      !existingConfigured.value.some(ec => ec.id === p.id) &&
      !selected.value.some(s => s.id === p.id)
  )
)

// 判断某项目是否已在 existingConfigured 中
function isConfigured(item) {
  return existingConfigured.value.some(p => p.id === item.id)
}
// 判断某项目是否已在本次 selected 中
function isSelected(item) {
  return selected.value.some(p => p.id === item.id)
}

// 点击“添加”
function select(item) {
  if (isConfigured(item)) {
    ElMessage.warning('该项目已在该级别中，无法添加')
    return
  }
  if (isSelected(item)) {
    ElMessage.warning('该项目已被选中')
    return
  }
  selected.value.push(item)
}

// 点击“移除”
function deselect(item) {
  selected.value = selected.value.filter(p => p.id !== item.id)
}

// 点击“确认”批量新增关联并返回列表页
async function confirmAdd() {
  if (selected.value.length === 0) {
    ElMessage.info('请先选中要添加的项目')
    return
  }
  try {
    const tasks = selected.value.map(p =>
      axios.post(
        '/CareLevelProjectController/addCareLevelProject',
        qs.stringify({
          careLevelId: levelId,
          careProjectId: p.id
        })
      )
    )
    await Promise.all(tasks)
    router.push({ path: '/LevelProjectList', query: { levelId } })
  } catch (err) {
    console.error(err)
    ElMessage.error('添加项目失败，请重试')
  }
}

// 点击“取消”返回列表页
function cancel() {
  router.push({ path: '/LevelProjectList', query: { levelId } })
}

// 初始化：先拉取已配置，再拉取所有启用项目
onMounted(async () => {
  try {
    // 1. 后端已配置
    const res1 = await axios.get('/CareLevelProjectController/getProjectsByLevel', {
      params: { careLevelId: levelId }
    })
    existingConfigured.value = res1.data.data

    // 2. 全部启用状态项目
    const res2 = await axios.get('/CareProjectController/queryByStatus', {
      params: { status: 1, cur: 1, number: 9999 }
    })
    fullList.value = res2.data.data
  } catch (err) {
    console.error(err)
    ElMessage.error('初始化数据加载失败')
  }
})
</script>

<style scoped>
.footer-btns {
  text-align: right;
  margin-top: 16px;
}
</style>
